package com.minelx.serverandclient.chatting;

import com.minelx.serverandclient.connector.SocketTubes;

import javax.swing.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executors;

public class Chatting {
	public static final int PORT = 8848;

	public static void main(String[] args) throws IOException {
		launchAsClient("192.168.11.100", PORT);
	}

	private static void selfConnection() throws IOException {
		Executors.newSingleThreadExecutor().submit(() -> {
			// start client
			try {
				Thread.sleep(1000);
				launchAsClient("localhost", PORT);
			} catch (IOException | InterruptedException e) {
				e.printStackTrace();
			}
		});

		launchAsServer(PORT);
	}

	private static void launchAsServer(int port) throws IOException {
		ServerSocket serverSocket = new ServerSocket(port);
		Socket connection = serverSocket.accept();
		runForm(new ChattingForm(new SocketTubes(connection)), "Server");
	}

	private static void launchAsClient(String host, int port) throws IOException {
		runForm(new ChattingForm(new SocketTubes(new Socket(host, port))), "Client - " + host + " - " + port);
	}

	private static void runForm(ChattingForm form, String title) {
		JFrame frame = new JFrame(title);
		frame.setContentPane(form.getPanel1());
		frame.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				form.close();
				frame.dispose();
			}
		});
		frame.pack();
		frame.setVisible(true);
	}
}
